import React, { useState, useRef, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns } from '@ant-design/pro-table'
import { connect } from 'umi'
import { message, Button, Modal, Form, Input, Row, Col, Select, Divider, Popconfirm } from 'antd'
import {saveAndEditContractGroup,getContractSubjectList,deleteContractGroup, queryContractGroupPage,queryContractSubGroupPage} from '../service'
const {Option} = Select;

const TableList = () => {
  const [finalTree,setFinalTree] = useState([]);
  const actionRef = useRef();
  const [form] = Form.useForm();
  const [title, setTitle] = useState('');
  const [visible, setVisible] = useState(null);
  const [id, setId] = useState(null);

  useEffect(() => {
    getContractSubjectList().then(res => {
      setFinalTree(res);
    });
  }, []);

  const addMainBody = () => {
    setVisible(true);
    setTitle('添加主体组');
  };

  const updateMainBody = (value) =>{
    setVisible(true);
    setTitle('编辑主体组');
    setId(value.id);
    queryContractSubGroupPage(value.id).then(res => {
      let temp = [];
      res.map(item => {
        temp.push(item.id.toString());
      });
      form.setFieldsValue({contractMainName:value.groupName,contractMainIds:temp});
    });
  };

  const delMainBody = (values) => {
    deleteContractGroup(values).then(r => {
      if (r.flag){
        message.success(`删除主体组成功。`);
      }else {
        message.error(`删除主体组失败。${r.error}`);
      }
      actionRef.current.reload();
    })
  };

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  };

  const handleCancel = () => {
    setVisible(false);
    setId(null);
    form.resetFields();
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    id ? fieldsValue.id = id : null;
    saveAndEditContractGroup(fieldsValue).then(res => {
      if(res.flag){
        form.resetFields();
        setVisible(false);
        setId(null);
        actionRef.current.reload();
        message.success(`操作成功`);
      }else{
        message.error(`主体组操作失败：` + res.error);
      }
    });
  };

  const columns = [
    {
      title: '序号',
      render:(text,record,index)=>`${index+1}`,
      hideInSearch: true,
      width: '20%'
    },
    {
      title: '主体组名称',
      dataIndex: 'groupName',
      width: '60%'
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: '20%',
      render: (item, record) => (
        <>
          {<a onClick={() => updateMainBody(record)}>编辑</a>}
          {<Divider type="vertical" />}
          {<Popconfirm title={`是否确认删除?`} onConfirm={() => delMainBody(record.id)} okText="是" cancelText="否">
            <a>删除</a>
          </Popconfirm>}
        </>
      ),
    },
  ];


  return (
    <PageHeaderWrapper>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={(params) => queryContractGroupPage(params)}
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" key={0} onClick={() => addMainBody()}>新建</Button>
        ]}
      />

      <Modal
        title={title}
        visible={visible}
        footer={null}
        closable={false}
      >
        <Form
          form={form}
          name="normal_login"
          className="login-form"
          onFinish={handleSubmit}
        >
          <Form.Item name="contractMainName" rules={[{required: true, message: '主体组名称不能为空'}]}>
            <Input placeholder="主体组名称" />
          </Form.Item>
          <Form.Item name="contractMainIds" rules={[{required: true, message: '主体不能为空'}]}>
            <Select placeholder="请选择主体" mode="multiple" showSearch filterOption={filterOption}>
              {finalTree.map((item, index) => {
                return (
                  <Option value={`${item.id}`} key={index}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          </Form.Item>
          <Row justify='end' gutter={16}>
            <Col className="gutter-row" style={{paddingBottom: '20px'}}>
              <Button style={{marginRight: '12px'}} onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">保存</Button>
            </Col>
          </Row>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  )
};

export default connect(({}) => ({
}))(TableList)
